/**
 * Copyright
 *
 * All rights reserved
 *
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under this License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations.
 *
 * This file originally written by Chetan Padhye
 *
 */

var w = 1500,
    h = 600,
    root,file_json;
var tooltip = Tooltip("vis-tooltip", 300);
var force = d3.layout.force()
    .linkDistance(450)
    .charge(-700)
    .gravity(2)
    .size([w, h]);
var nodes,links;
var force, link, node;
var vis = d3.select("#grapharea").append("svg:svg")
    .attr("width", w)
    .attr("height", h);


//Dom ready Function
$(function () {
	d3.json("./data/tmp-connections.json", function(tmp_json) {
		  file_json = tmp_json;
		  json =  prosess(file_json,1);
		  root = json;
		  update();
	});
    
});
var result_json = {};
result_json['children'] = [];
var tickArr = [1];
function prosess(file_json, start_id) {
	tickArr.push(start_id);
	if (start_id === 1) {

		start = file_json.nodes[start_id - 1];
		$.extend(result_json, start);

		jQuery.grep(file_json.links, function(element, index) {
			if (element["source"] === start_id) {
				obj = file_json.nodes[element['target'] - 1];
				obj.linkinfo = element;
				if(result_json['children'])
				result_json['children']
						.push(file_json.nodes[element['target'] - 1]);
			}
		});

	}else{
		jQuery.grep(result_json['children'],function(element1, index){
			
			if(element1.id === start_id){
				tmp_c = file_json.nodes[start_id - 1];
				tmp_c['children'] = [];
				
				jQuery.grep(file_json.links, function(element, index) {
					if (element["source"] === start_id) {
						obj = file_json.nodes[element['target'] - 1];
						obj.linkinfo = element;
						tmp_c['children']
								.push(file_json.nodes[element['target'] - 1]);
					}
				});
			}
		});
		
	}
	// json = result_json;
	//console.log(JSON.stringify(result_json));

	return result_json;
}




function update() {
   if(force)
	force.stop();
   if(link) 
   link.remove();
   if (node) 
   node.remove();
    
    
		nodes = flatten(root);
      links = d3.layout.tree().links(nodes);

  // Restart the force layout.
  force
      .nodes(nodes)
      .links(links)
      .start();

  // Update the links…
   link = vis.selectAll("line.link")
      .data(links, function(d) { return d.target.id; });

  // Enter any nshowDetailsew links.
  link.enter().insert("svg:line", ".node")
      .attr("class", function(d){return 'link '+ d.target.linkinfo.classname;})
      .attr("x1", function(d) { return d.source.x; })
      .attr("y1", function(d) { return d.source.y; })
      .attr("x2", function(d) { return d.target.x; })
      .attr("y2", function(d) { return d.target.y; });
  
  link.on("click", showDetailsLink);

  // Exit any old links.
  link.exit().remove();

  // Update the nodes…
   node = vis.selectAll("g.node")
      .data(nodes, function(d) { return d.id; })

  // Enter any new nodes.
  var nodeEnter = node.enter().append("svg:g")
      .attr("class", "node")
      .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
      .on("click", click)
      .call(force.drag);

  
  nodeEnter.append("image")
  .attr("xlink:href", function (d) {
      return "img/" + d.icon;
  })
  .attr("x", function (d) {
  	return  - (d.icon.split('_')[3] / 2);
  })
  .attr("y",  function (d) {
  	return  - (d.icon.split('_')[3] / 2);
  })
  .attr("width", function (d) {
  	return d.icon.split('_')[3];
  })
  .attr("height", function (d) {
  	return d.icon.split('_')[3];
  });

  nodeEnter.append("svg:text")
      .attr("text-anchor", "middle")
      .attr("dy", ".35em")
      .attr("fill", "#000")
      .attr("dx", 12)
      .text(function(d) { return d.name; });
  //node.on("click", showDetails);
  // Exit any old nodes.
  node.exit().remove();

  // Re-select for update.
  link = vis.selectAll("line.link");
  node = vis.selectAll("g.node");

  force.on("tick", function() {
    link.attr("x1", function(d) { return d.source.x; })
        .attr("y1", function(d) { return d.source.y; })
        .attr("x2", function(d) { return d.target.x; })
        .attr("y2", function(d) { return d.target.y; });

    node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
  });
}


function showDetails(d, i) {
	if (d.name !== undefined) {
        // Node
        content = '<p class="main"><span class="left">' + d.name + '</span></p>';
    } else {
        //link
        content = '<p class="main"><span class="left">' + 'Relationship Edge' + '</span></p>';
    }
    content += '<hr class="tooltip-hr">';
    content += '<div class="tipcontent">';
    $.each(d, function (k, v) {
        // display the key and value pair
    	 if ($.inArray(k, ['Name','name', 'Company', 'Location', 'Job Title','Job Level', 'SME Primary','SME Secondary','Political Power', 'Department', 'Drivers - Risk','Drivers - Reputation','Drivers - Horizons','Personal Agenda', 'FoT', 'Relationship Strength', 'Start Date']) != -1) {
             content += '<p class="caps"><span class="bold">' + k + ':</span><span>  ' + v + ' </span></p>';
         }
    });
    content += '</div>';
    $('.connectioninfo_js').html(content);
}


function showDetailsLink(d, i) {

	// link
	content = '<p class="main"><span class="left">' + 'Relationship Edge'
			+ '</span></p>';

	content += '<hr class="tooltip-hr">';
	content += '<div class="tipcontent">';
	$.each(d,
			function(k, v) {
				// display the key and value pair
				if ($.inArray(k, [ 'Name', 'name', 'Company', 'Location',
						'Job Title', 'Department', 'FoT',
						'Relationship Strength', 'Start Date' ]) != -1) {
					content += '<p class="caps"><span class="bold">' + k
							+ ':</span><span>  ' + v + ' </span></p>';
				}
			});
	content += '</div>';
	$('.connectioninfo_js').html(content);
}


function hideDetails(d, i) {
    tooltip.hideTooltip()
}
// Toggle children on click.
function click(d) {
  if (d.children) {
    d._children = d.children;
    d.children = null;
  } else {
    d.children = d._children;
    d._children = null;
  }
  if($.inArray(d.id, tickArr)!=1){
	  force.stop();
	  link.remove();
	  node.remove();
	  force.start();

	  json =  prosess(file_json,d.id);
	  root = json;
	  update();
  }else{
	  
	  // remove child logic
  }
  
  showDetails(d);
}

// Returns a list of all nodes under the root.
function flatten(root) {
  var nodes = [], i = 0;

  function recurse(node) {
    if (node.children) node.children.forEach(recurse);
    if (!node.id) node.id = ++i;
    nodes.push(node);
  }

  recurse(root);
  return nodes;
}